<!--
 * @Author: zqx me_zqx@163.com
 * @Date: 2025-04-25 10:48:08
 * @LastEditors: zqx me_zqx@163.com
 * @LastEditTime: 2025-05-13 16:22:01
 * @FilePath: /XMate-h5/src/views/messageCenter/messageDetail/index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div :class="`flex flex-col h-screen justify-between bg-white`">
    <div v-if="isPC()">
      <div v-if="isElectron() && isMac()" class="mac-titlebar"></div>
      <div class="flex flex-row justify-between items-center h-[44px] px-4 shadow-sm">
        <van-icon name="arrow-left cursor-pointer" @click="onClickBack" />
        <h4 class="text-sm font-medium">实时总结详情</h4>
        <div />
      </div>
    </div>
    <div class="flex-auto mt-4 overflow-y-auto page-content">
      <div class="px-4 header">
        <div class="p-4 rounded-lg bg-[#FAFAFA]">
          <div class="flex flex-col px-4 gap-2 text-sm">
            <div class="flex flex-row items-center">
              <h4 class="text-[#8C8C8C] text-sm mr-2.5 w-[60px] min-w-[60px]">
                沟通主题
              </h4>
              <p class="text-[#262626] text-sm">{{ msgDetail.subject || "-" }}</p>
            </div>

            <div class="flex flex-row items-center">
              <h4 class="text-[#8C8C8C] text-sm mr-2.5 w-[60px] min-w-[60px]">
                客户名称
              </h4>
              <p class="text-[#262626] text-sm">{{ msgDetail.customerName || "-" }}</p>
            </div>

            <div class="flex flex-row items-center">
              <h4 class="text-[#8C8C8C] text-sm mr-2.5 w-[60px] min-w-[60px]">创建人</h4>
              <p class="text-[#262626] text-sm">
                {{ msgDetail.confHostUserName || "-" }}
              </p>
            </div>

            <div class="flex flex-row items-center">
              <h4 class="text-[#8C8C8C] text-sm mr-2.5 w-[60px] min-w-[60px]">
                开始时间
              </h4>
              <p class="text-[#262626] text-sm">{{ msgDetail.confCreatedTime || "-" }}</p>
            </div>
          </div>
        </div>
      </div>
      <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
        <van-list
          class="h-full"
          v-model:loading="loading"
          :finished="finished"
          @load="loadData"
        >
          <div class="px-4" :key="listKey">
            <msgDetailCell v-for="item in cp_list" :item="item" :key="item.id" />
          </div>

          <template v-slot:finished>
            <div v-if="!confIsDone" class="flex flex-row justify-start pl-4">
              <van-loading v-if="isReceiveNewMsg" size="24px"
                >正在录制，每10分钟或录制文本超300字生成总结。</van-loading
              >
              <p v-else class="text-sm text-[#8C8C8C]">已停止</p>
            </div>
          </template>
        </van-list>

        <van-back-top right="40px" bottom="150px" style="background-color: #436bff" />
      </van-pull-refresh>
    </div>

    <div class="w-full px-4 pb-10 pt-3 shadow-t bg-white" v-if="!confIsDone">
      <van-button
        type="primary"
        :disabled="btnLoading"
        :loading="btnLoading"
        size="large"
        color="#436BFF"
        @click="onBtnClick"
        >{{ btnText }}</van-button
      >
    </div>
  </div>
</template>

<script setup lang="ts">
import msgDetailCell from "./msgDetailCell.vue";
import { ref, computed, onMounted, onUnmounted, nextTick } from "vue";
import { useWebSocket } from "@vueuse/core";
import { useRouter, useRoute } from "vue-router";
import { showToast } from "vant";
// @ts-ignore
import { getToken } from "@/utils/auth";
// @ts-ignore
import { SocketEventType } from "@/services/socketEvent";
// @ts-ignore
import { isElectron, isMac, isPC, getPlatform } from "@/utils/platformTool";
// @ts-ignore
import { loadInfoFromPC } from "@/utils/electronTool";
// @ts-ignore
import { getMsgDetail, enableMsgAPI, disableMsgAPI } from "@/services/msgCenter";
// @ts-ignore
import { MsgDetailResponse, MsgModel } from "@/services/msgCenter/type";
import dayjs from "dayjs";
// @ts-ignore
import { useCustomWebSocket } from "@/composables/useWebSocket";

// 添加定时器引用
const timer = ref<NodeJS.Timer | null>(null);

// 添加一个标记来追踪是否可以自动滚动
const canAutoScroll = ref(true);
let listDom: any;

// 连接socket
const { connect, disconnect, isConnected } = useCustomWebSocket({
  onMessage(eventType: String, eventData: any) {
    console.log("onMessage", eventType, eventData);
    if (eventType == SocketEventType.XMATE_CONF_SUMMARY_MSG) {
      const { hostUserId, type, orgId, content, bizId: confId } = eventData;
      if (confId !== id) {
        return;
      }

      handleNewMsg({
        content,
        createdTime: dayjs().format("YYYY-MM-DD HH:mm:ss"),
      });
    }

    if (eventType == SocketEventType.XMATE_CONF_SUMMARY_MSG_DISABLE) {
      const [confId, status] = eventData.split(":");
      if (confId !== id) {
        return;
      }
      isReceiveNewMsg.value = status === 0;
    }
  },
});

onMounted(() => {
  connect(); // 连接WebSocket
  if (isElectron()) {
    loadInfoFromPC(() => loadData());
  } else {
    loadData();
  }

  // 启动定时刷新
  startAutoRefresh();
  nextTick().then(() => {
    listDom = document.querySelector(".page-content");
    // 添加滚动事件监听
    if (listDom) {
      listDom.addEventListener("scroll", onScroll);
    }
  });
});

const pageContent = ref(null);
// 清理事件监听
onUnmounted(() => {
  disconnect(); // 断开WebSocket连接
  if (timer.value) {
    clearInterval(timer.value as number);
    timer.value = null;
  }

  if (listDom) {
    listDom.removeEventListener("scroll", onScroll);
  }
});

// 处理滚动事件
function onScroll() {
  canAutoScroll.value = false;

  // 3秒后恢复自动滚动
  setTimeout(() => {
    canAutoScroll.value = true;
  }, 3000);
}

// 用来强制刷新列表UI
const listKey = ref(0);
function startAutoRefresh() {
  timer.value = setInterval(() => {
    // 强制组件重新渲染
    // 用于更新cell中的【xx分钟前】
    listKey.value++;
    scrollToBottom();
  }, 25000);
}

// 修改滚动到底部函数
function scrollToBottom() {
  if (!canAutoScroll.value) {
    return;
  }

  nextTick(() => {
    if (listDom) {
      listDom.scrollTo({
        top: listDom.scrollHeight,
        behavior: "smooth",
      });
    }
  });
}

const router = useRouter();
const route = useRoute();
const { id } = route.query;
const msgDetail = ref<MsgDetailResponse>({});
function onClickBack() {
  router.replace("/msgCenter/msgList");
}

const refreshing = ref(false);
const loading = ref(false);
const finished = ref(false);
// 是否接受新消息
const isReceiveNewMsg = ref(true);

function onRefresh() {
  loadData();
}

async function loadData() {
  if (!id) {
    showToast("id 为空");
    return;
  }

  refreshing.value = true;
  loading.value = true;

  msgDetail.value = await getMsgDetail(id);
  list.value = msgDetail.value.msgList;
  isReceiveNewMsg.value = msgDetail.value.disableRealTimePush !== 1;

  setTimeout(() => {
    scrollToBottom();
  }, 2000);

  if (isPC()) {
    try {
      const ipcRenderer = window.nodeRequire("electron").ipcRenderer;
      ipcRenderer.send("forward_message", {
        to: "main",
        message: { action: "reload_schedule", data: "" },
      });
    } catch (e) {}
  }

  refreshing.value = false;
  loading.value = false;
  finished.value = true;
}

const confStatus = computed(() => {
  return msgDetail.value.confStatus;
});

const confIsDone = computed(() => {
  return confStatus.value === 1;
});

const btnText = computed(() => {
  return isReceiveNewMsg.value ? "停止接收" : "重新接收";
});

// 修改 handleNewMsg 函数
function handleNewMsg(v: any) {
  console.log("handleNewMsg", v);
  list.value.push(v);
  // 收到新消息后滚动到底部
  scrollToBottom();
}

function onBtnClick() {
  if (isReceiveNewMsg.value) {
    stopReceiveMsg();
  } else {
    startReceiveMsg();
  }
}

const btnLoading = ref(false);
// 停止接收消息
async function stopReceiveMsg() {
  btnLoading.value = true;
  try {
    const success = await disableMsgAPI(id);
    if (success === true) {
      isReceiveNewMsg.value = false;
    }
  } catch (error) {
    console.error(error);
  } finally {
    btnLoading.value = false;
  }
}

// 开始接收消息
async function startReceiveMsg() {
  btnLoading.value = true;
  isReceiveNewMsg.value = true;
  try {
    const success = await enableMsgAPI(id);
    if (success === true) {
      isReceiveNewMsg.value = true;
    }
  } catch (error) {
    console.error(error);
  } finally {
    btnLoading.value = false;
  }
}

const cp_list = computed(() => {
  return list.value.sort((a: MsgModel, b: MsgModel) => {
    return dayjs(a.createdTime).isBefore(dayjs(b.createdTime)) ? -1 : 1;
  });
});
const list = ref(<MsgModel>[]);
</script>

<style scoped lang="less">
.mac-titlebar {
  -webkit-app-region: drag;
  height: 30px;
  display: flex;
  font-weight: 500;
  justify-content: center;
  align-items: center;
  width: 100%;
  z-index: 10;
}
</style>
